
package com.bbcare.followup.plat.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.bbcare.comm.*;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import com.bbcare.followup.plat.entity.FollowQueue;
import com.bbcare.followup.plat.entity.Patient;
import com.bbcare.followup.plat.entity.PatientQueueScheme;
import com.bbcare.followup.plat.entity.PatientTask;
import com.bbcare.followup.plat.entity.PatientTaskContent;
import com.bbcare.followup.plat.entity.PbUserInfo;
import com.bbcare.followup.plat.service.IFollowQueueService;
import com.bbcare.followup.plat.service.IPatientInfoHisService;
import com.bbcare.followup.plat.service.IPatientService;
import com.bbcare.followup.plat.service.IScanDataSynchService;
import com.bbcare.followup.plat.store.ibatis.IContentTemplDAO;
import com.bbcare.followup.plat.store.ibatis.IFollowQueueDAO;
import com.bbcare.followup.plat.store.ibatis.IPatientQueueSchemeDAO;
import com.bbcare.followup.plat.store.ibatis.IPatientTaskContentDAO;
import com.bbcare.followup.plat.store.ibatis.IPatientTaskDAO;
import com.bbcare.treat.plat.entity.FuQueueScheme;
import com.bbcare.treat.plat.entity.PtTrTask;
import com.bbcare.treat.plat.entity.TrTaskContent;
import com.bbcare.treat.plat.service.IPatientTreatService;
import com.bbcare.treat.plat.service.IPtTaskTreatService;
import com.bbcare.treat.plat.store.ibatis.IFuQueueSchemeDAO;
import com.bbcare.treat.plat.store.ibatis.IPtTrTaskDAO;
import com.bbcare.treat.plat.store.ibatis.ITrTaskContentDAO;

/**
 *
 * @name:         mq消费服务类
 * @author:       tao
 * @createTime:   2017年12月20日
 * @description:  MqConsumerService.java
 * @modify:
 *
 */
@Service
public class ScanDataSynchService implements IScanDataSynchService {
    private static final Log logger = LogFactory.getLog(ScanDataSynchService.class);

    @Autowired
    private IFollowQueueDAO queueDao;

    @Autowired
    private IPatientTreatService patientTreatService;

    @Autowired
    private IPatientService patientService;

    @Autowired
    private IPatientQueueSchemeDAO patientQueueSchemeDao;

    @Autowired
    private IFuQueueSchemeDAO IFuQueueSchemeDAO;

    @Autowired
    private IPatientTaskDAO patientTaskDao;

    @Autowired
    private IFollowQueueService followQueueSerivce;

    @Autowired
	private IPatientTaskContentDAO patientTaskConDao;

    @Autowired
	private IContentTemplDAO contentTemplDao;

    @Autowired
	private IPtTaskTreatService ptTaskTreatService;

    @Autowired
   	private IPtTrTaskDAO ptTrTaskDAO;



    @Autowired
    private ITrTaskContentDAO trTaskContentDao;

    @Autowired
    private IPatientInfoHisService patientInfoHisService;

	@Override
	@Transactional
	public void consumerAddPatientByScan(String receiveStr) throws Exception {
		logger.info("in consumerAddPatientByScan");
		//解析传入数据
		JSONObject json = JSON.parseObject(receiveStr);
		JSONObject commParam = json.getJSONObject(Constants.MQ_MESSAGE_BODY);
		JSONArray userList = json.getJSONArray("userList");
		String createTime = DateUtil.getSysDateA();
		//多个用户和建档数据  循环
		Map<String,Object> userParam = new HashMap<String,Object>(); //查询用户是否存在
		if(null != userList){
			for(int i = 0,n=userList.size() ;i<n ; i++){
				PbUserInfo userInfo = userList.getJSONObject(i).getObject("userInfo",PbUserInfo.class);
				JSONObject contentMap = userList.getJSONObject(i).getJSONObject("contentMap");

				userParam.put("userId", userInfo.getId());
				userParam.put("tenantId",userInfo.getTenantId());
				Patient patient = patientService.getPatient(userParam);// 根据userId查询 ;
				if(null != patient){
					//并且还在队列中  则跳过本次  更新直接走更新流程
					userParam.clear();
					userParam.put("userId", userInfo.getId());
					List<String> statulist = new ArrayList<String>();
					statulist.add(Constants.PATIENT_QUEUESCHEME_USER_STATUS_NOMAL);
					userParam.put("status", statulist);
					List<PatientQueueScheme> patientScheme = patientQueueSchemeDao.selectByUserId(userParam);
					if(!CollectionUtils.isEmpty(patientScheme)){
						logger.error("队列中已经存在该用户--userId="+userInfo.getId());
						continue; //可以改成修改建档资料
					}
				}

				//查询队列级 建档问卷信息和 建档问卷同步权限
				Map<String,Object> ruleMap = dataSynchPermission(userInfo.getQueueId(),Constants.OP_CODE_1000,Constants.PATIENT_DATA_RULE_TYPE_PUT);
				if(!(boolean) ruleMap.get("flag")){
					logger.error("队列没有配置建档同步提交权限[queueId="+userInfo.getQueueId()+",userId="+userInfo.getId());
					return;
				}

				int schemeBusiType
				= (org.springframework.util.StringUtils.isEmpty(ruleMap.get("schemeBusiType")))?Constants.SCHEME_BUSI_TYPE_0:Integer.parseInt(ruleMap.get("schemeBusiType").toString());

//				List<Map<String,Object>> schemeList = new ArrayList<Map<String,Object>>();

				//封装方法patientTreatService所需的入参
				Patient pt = new Patient();
				pt.setUserName(userInfo.getUserName());
				pt.setPhoneNo(userInfo.getPhoneNo());
				pt.setFirstName(userInfo.getUserName().substring(0, 1));
				pt.setCreateTime(createTime);
				pt.setUpdateTime(createTime);
				pt.setCreateAuthor(userInfo.getId());
				pt.setBirthday(userInfo.getBirthday());
				pt.setExpectedDay(userInfo.getExpectedDay());
				pt.setGender(userInfo.getGender());
				pt.setUserType(userInfo.getUserType());
				pt.setSourceType(userInfo.getSourceType()); //扫码建档
				pt.setPregnancyDay(userInfo.getPregnancyDay());
				pt.setId(userInfo.getId());
//				pt.setWechat_id(openId);

				Map<String,Object> servParamMap = new HashMap<String,Object>();
				servParamMap.put("babyName",userInfo.getUserName());
//				servParamMap.put("openId",openId);
				servParamMap.put("phoneNum",userInfo.getPhoneNo());

				servParamMap.put("patient", pt);
				servParamMap.put("authorName",userInfo.getUserName());
				servParamMap.put("deptId", userInfo.getDeptId());
				servParamMap.put("queueId", userInfo.getQueueId());
				servParamMap.put("updateTime", createTime);
				servParamMap.put("authorId",userInfo.getId());
				servParamMap.put("tenantId", userInfo.getTenantId());

				servParamMap.put("updateAccept",commParam.get("updateAccept")+"-"+i);
				servParamMap.put("opCode", commParam.get("opCode"));
				if(userList.size() == 1){
					servParamMap.put("opNote", commParam.get("opNode"));//多个用户时  不用此值
				}
				servParamMap.put("contentData", contentMap);
				servParamMap.put("userType",userInfo.getUserType());
				servParamMap.put("sourceType", userInfo.getSourceType());

				logger.info("扫码建档：" + servParamMap.toString());

				//根据方案类型 调用不同的接口
				if (Constants.SCHEME_BUSI_TYPE_0 == schemeBusiType) {
					//扫码端问卷和医生端问卷 转换
					//问卷查询
					Map<String,Object> contentParam = new HashMap<String,Object>();
					contentParam.put("schemeId",ruleMap.get("schemeId"));
					contentParam.put("queueId", userInfo.getQueueId());
					Map<String,Object> contMapOut = followQueueSerivce.qryQueueSchemePatientAddContent(contentParam);
//			        List<Object> contMapOutList =patientService.getContTempDataByTaskId(queueId,taskId) ;
					//
					Map<String,Object> contentMapTemp = questionContentConvert(contentMap,userInfo.getQueueId(),contMapOut,Constants.MQ_MESSAGE_GET_FROM_SCAN);
					servParamMap.put("contentData",contentMapTemp);

					patientService.registerPatient(servParamMap);
	            } else if (Constants.SCHEME_BUSI_TYPE_1 == schemeBusiType) {
	            	userParam.clear();
	            	userParam.put("queueId", userInfo.getQueueId());
	            	List<FuQueueScheme> listone = IFuQueueSchemeDAO.getTrSchemeBusiTypeByQueueId(userParam);
	            	List<Map<String, Object>> listTow = new ArrayList<Map<String, Object>>();
	            	// 查询当前队列的方案类型
	            	if (listone != null && listone.size() > 0) {
	                    for (int j = 0; j < listone.size(); j++) {
	                         Map<String, Object> mapOne = new HashMap<String, Object>();
	                         FuQueueScheme fu = listone.get(i);
	                         mapOne.put("schemeBusiType", fu.getSchemeBusiType());
	                         mapOne.put("schemeId", fu.getSchemeId());
	                         listTow.add(i, mapOne);
	                     }
	            	}
	            	servParamMap.put("schemeList",listTow);

	            	//扫码端问卷和医生端问卷 转换
	            	//门诊扫码建档   增加问卷字段根据配置关系 映射  start
	    	        String archiveTemplId = (String) ruleMap.get("archiveTemplId");
	    	        String archiveTemplIdArr[] = archiveTemplId.split(Constants.COMMA_SPLIT_STR);
	    	        List<String> archiveTemplIdList = java.util.Arrays.asList(archiveTemplIdArr);
	    	        Map<String, Object> contMapIn = new HashMap<String, Object>();
	    	        contMapIn.put("templIdList", archiveTemplIdList);
	    	        Map<String, Object> contMapOut = patientTreatService.getContentTemplData(contMapIn); //问卷
	    	        Map<String,Object> contentMapTemp = questionContentConvert(contentMap,userInfo.getQueueId(),contMapOut,Constants.MQ_MESSAGE_GET_FROM_SCAN);
					servParamMap.put("contentData",contentMapTemp);
	            	patientTreatService.savePatientArchives(servParamMap);
	            }
			}
		}
		logger.info("out consumerAddPatientByScan");
	}

	@Override
	@Transactional
	public void consumerTaskContDataByScan(String receiveStr) throws Exception {
		logger.info("in consumerTaskContDataByScan");
		//解析传入数据
		JSONObject json = JSON.parseObject(receiveStr);
		JSONObject commParam = json.getJSONObject(Constants.MQ_MESSAGE_BODY);
		String sourceType = json.getString("sourceType");
		JSONObject questions = commParam.getJSONObject("questions");

		String createTime = DateUtil.getSysDateA();
//		Map<String,Object> userParam = new HashMap<String,Object>();
		//判断用户是否存在 不存在则不处理

		String queueId = commParam.getString("queueId");
		String userId = commParam.getString("userId");

		//查询队列级 主诉问卷同步权限  --问卷中个别参数级 在后续接口中处理

		//查询队列级 建档问卷信息和 建档问卷同步权限  --问卷中个别参数级 在后续接口中处理
		Map<String,Object> ruleMap = dataSynchPermission(queueId,Constants.OP_CODE_1009,Constants.PATIENT_DATA_RULE_TYPE_PUT);
		if(!(boolean) ruleMap.get("flag")){
			logger.error("队列没有配置主诉同步提交权限[queueId="+queueId+",userId="+userId);
			return;
		}
		String tenantId = (String)ruleMap.get("tenantId");
		int schemeBusiType = (org.springframework.util.StringUtils.isEmpty(ruleMap.get("schemeBusiType")))?Constants.SCHEME_BUSI_TYPE_0:Integer.parseInt(ruleMap.get("schemeBusiType").toString());
		Map<String,Object> ptMap = new HashMap<String,Object>();
		ptMap.put("userId",userId);
		ptMap.put("tenantId",tenantId);
		ptMap.put("queueId",queueId);
		List<String> statulist = new ArrayList<String>();
		statulist.add(Constants.PATIENT_QUEUESCHEME_USER_STATUS_NOMAL);
		ptMap.put("status", statulist);
		List<PatientQueueScheme> queueSchemeList = patientQueueSchemeDao.selectByUserId(ptMap);
		String ptSchemeId = null;
		if(!CollectionUtils.isEmpty(queueSchemeList)){
			ptSchemeId =  queueSchemeList.get(0).getId();
		}else{
			logger.error("out consumerTaskContDataByScan-->无用户数据");
			return;
		}

		Map<String,Object> servParamMap = new HashMap<String,Object>();
//		servParamMap.put("openId",openId);

		String updateAccept = (String)commParam.get("updateAccept");
		String updateTime = createTime;
		String  deptId = (String)ruleMap.get("deptId");
		servParamMap.put("deptId", deptId);
		servParamMap.put("userId", userId);
		servParamMap.put("queueId", queueId);
		servParamMap.put("updateTime",updateTime);
		servParamMap.put("authorId",userId);
		servParamMap.put("tenantId", tenantId);
		servParamMap.put("updateAccept",updateAccept);
		servParamMap.put("opCode", commParam.get("opCode"));
		servParamMap.put("opNote", commParam.get("opNode"));//
		servParamMap.put("opType", commParam.get("opType"));//
		servParamMap.put("sourceType", sourceType);//
		//随访  查询当前时间段 随访任务id
		if (Constants.SCHEME_BUSI_TYPE_0 == schemeBusiType) {
			//
			ptMap.clear();
			ptMap.put("ptSchemeId", ptSchemeId);
			ptMap.put("endTime", DateUtil.getCurrDate());
			ptMap.put("beginTime", DateUtil.getCurrDate());
			ptMap.put("seqNoOrderAsc", "seqNoOrderAsc");
			ptMap.put("taskType", "0");
//			ptMap.put("taskStatus", "0");
			ptMap.put("revSeqNo", 0);// 去掉建档任务
			// 查询所有的任务信息
			List<PatientTask> ptVoList = patientTaskDao.select(ptMap);

			String taskId ="";
			if (CollectionUtils.isEmpty(ptVoList)) {
				//新建临时任务
				logger.error("out consumerTaskContDataByScan-->没有任务");

				//无任务 增加临时任务
				Map<String,Object> map = new HashMap<String,Object>();
				map.put("ptSchemeId",ptSchemeId);
				map.put("queueId",queueId);
				map.put("userId",userId);
				map.put("tenantId",tenantId);

				map.put("updateAccept",updateAccept+"-1");
				map.put("updateTime",updateTime);

				Map<String,Object> taskIdMap = this.saveTempTaskAndRspTaskId(map);
				if(!MapUtils.isEmpty(taskIdMap) && null != taskIdMap.get("newTaskId")){
					taskId = (String)taskIdMap.get("newTaskId");
				}
			}else{
				ptMap.clear();
				taskId =ptVoList.get(0).getId();

				// 任务审核状态
		        String taskAuditStatus = ptVoList.get(0).getAuditStatus();
		        if (StringUtils.isEmpty(taskAuditStatus)) {
		            taskAuditStatus = Constants.PATIENT_TASK_AUDIT_STATUS_INIT;
		        } else if (Constants.PATIENT_TASK_AUDIT_STATUS_NORMAL.equals(taskAuditStatus)) {
		            // 已审核通过
		            if (Constants.PATIENT_SOURCE_TYPE_SCAN.equals(sourceType)) {
		                // 诊间扫码渠道
		                throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_PT_SACN_SYNC_DATA_FOR_AUDITED,
		                        "患者填写信息医生已确认，无法同步修改！"));
		            }
		        }
			}

			ptMap.put("taskId",taskId);
			// 查询随访方案任务内容
			List<PatientTaskContent> ptcList = patientTaskConDao.selectContentByTaskId(ptMap);
			if (CollectionUtils.isEmpty(ptcList)) {
				logger.error("out consumerTaskContDataByScan-->没有任务内容");
				return;
			}
			List<Object> conDataList = new ArrayList<Object>();
			Map<String, Object> outCtvMap = new HashMap<String, Object>(); //ctvList.get(0);
			int ipt = 0;
            int isize = ptcList.size();
            Map<String, Object> dataOut = new HashMap<String, Object>();
			for (ipt = 0; ipt < isize; ipt++) {
                PatientTaskContent ptaskc = ptcList.get(ipt);
                String templVersionId = ptaskc.getTemplVersionid();

                ptMap.clear();
                ptMap.put("templVersionId", templVersionId);
                dataOut = patientService.getContTemplData(ptMap);
                if (null != dataOut.get("contData")) {
                    conDataList.add(dataOut.get("contData"));
                }
            }
			outCtvMap.put("questiones", conDataList);

			Map<String,Object> contentMapTemp =  questionContentConvert(questions,queueId,outCtvMap,Constants.MQ_MESSAGE_GET_FROM_SCAN);
			if(MapUtils.isEmpty(contentMapTemp)){
				logger.error("主诉内容转换后 提交到医生端内容为空-->[queueId="+queueId+",userId="+userId);
				throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"主诉内容转换后 提交到医生端内容为空");//回滚临时任务
//				return;
			}
			String finishDate = DateUtil.getDate_8(new Date());
			servParamMap.put("ptSchemeId", ptSchemeId);
			servParamMap.put("taskId", taskId);
			servParamMap.put("type", Constants.QUESTIONNAIRE_TYPE_0);
			servParamMap.put("contentData",contentMapTemp);
			servParamMap.put("finishDate", finishDate);
			patientService.modTaskContentData(servParamMap);

		}else if (Constants.SCHEME_BUSI_TYPE_1 == schemeBusiType) {//门诊方案  查询当前时间段诊疗任务
			//  按规则配置表里面 配置对应的任务  前端传入的字段进行 关联

			Map<String, Object> param = new HashMap<String, Object>();
			param.put("followQueueId",queueId);
			param.put("schemeBusiType",schemeBusiType);
			param.put("ptSchemeId",ptSchemeId);
			Map<String, Object> secialTask = patientTreatService.listSpecialTask(param);

			if(MapUtils.isEmpty(secialTask) || null == secialTask.get("rows")){
				logger.error("医生端未配置诊疗任务[queueId="+queueId+",userId="+userId);
				return;
			}

			//根据配置规则查找任务id
			String taskId=""; //查询出问卷

			if(null == ruleMap.get("busiId")){
				logger.error("诊疗没有配置关联的任务id");
				return;
			}
			taskId = (String)ruleMap.get("busiId");
			String ptTaskId = "";//任务实例id
			param.clear();
			param.put("userId",userId);
			param.put("taskId",taskId);
			String lastTime ="";
			List<PtTrTask> ptTaskList = ptTrTaskDAO.getOprationHistoryList(param);
			if(!CollectionUtils.isEmpty(ptTaskList)){
				taskId = ptTaskList.get(0).getTaskId();
				lastTime = ptTaskList.get(0).getFinishDate();

				String dayTime = DateUtil.getCurrDate2();
				if(dayTime.equals(lastTime)){
					ptTaskId = ptTaskList.get(0).getId();
				}
			}
			/*else{//去掉任务序号为0  建档的任务  默认取第一个
				List<Map<String, Object>> taskList = (List<Map<String, Object>>)secialTask.get("rows");
				for(int i = 0,n=taskList.size();i<n;i++){
					if((Constants.TASK_SEQ_FOR_FIRST+"").equals(taskList.get(i).get("seq_no").toString())){
						taskId = (String)taskList.get(i).get("task_id");
					}
				}
			}*/

			param.clear();
			param.put("taskId",taskId);
			param.put("schemeBusiType",schemeBusiType);
	        Map<String, Object> contMapOut = ptTaskTreatService.qryTaskContent(param);
	        if(MapUtils.isEmpty(contMapOut) || null == contMapOut.get("questiones")){
	        	logger.error("没有配置主诉问卷");
				return;
	        }

//	        Map<String, Object> questionMap = (Map<String, Object>)contMapOut.get("questiones");
	        Map<String, Object> contentMapTemp = null;
			//是否有更新权限
			contentMapTemp = questionContentConvert(questions,queueId,contMapOut,Constants.MQ_MESSAGE_GET_FROM_SCAN);

 			servParamMap.put("ptSchemeId", ptSchemeId);
			servParamMap.put("task", taskId);//诊疗任务id
			servParamMap.put("taskId",ptTaskId);//任务实例id
			servParamMap.put("type", Constants.QUESTIONNAIRE_TYPE_0);
			servParamMap.put("contentData",contentMapTemp);
			if(MapUtils.isEmpty(contentMapTemp)){
				logger.error("主诉内容转换后 提交到医生端内容为空-->[queueId="+queueId+",userId="+userId);
				return;
			}
			ptTaskTreatService.submitTaskFunciton(servParamMap);
		}
	}

	@Override
	@Transactional
	public void consumerModifyPatientByScan(String receiveStr) throws Exception {
		logger.info("in consumerModifyPatientByScan");
		//解析传入数据
		JSONObject json = JSON.parseObject(receiveStr);
		JSONObject commParam = json.getJSONObject(Constants.MQ_MESSAGE_BODY);
//		JSONArray userList = json.getJSONArray("userList");
		String sourceType = json.getString("sourceType");
		JSONObject questions = json.getJSONObject("questions");
		String createTime = DateUtil.getSysDateA();

		if(null == commParam){
			return;
		}

		String userId  = commParam.getString("userId");
		String queueId  = commParam.getString("queueId");

		//查询用户是否存在  不存在不处理
		//查询队列级 建档问卷信息和 建档问卷同步权限  --问卷中个别参数级 在后续接口中处理
		Map<String,Object> ruleMap = dataSynchPermission(queueId,Constants.OP_CODE_1000,Constants.PATIENT_DATA_RULE_TYPE_PUT);
		if(!(boolean) ruleMap.get("flag")){
			logger.error("队列没有配置建档更新权限[queueId="+queueId+",userId="+userId);
			return;
		}

		int schemeBusiType = (org.springframework.util.StringUtils.isEmpty(ruleMap.get("schemeBusiType")))?Constants.SCHEME_BUSI_TYPE_0:Integer.parseInt(ruleMap.get("schemeBusiType").toString());

		Map<String,Object> servParamMap = new HashMap<String,Object>();
//		servParamMap.put("openId",openId);

		String  deptId = (String)ruleMap.get("deptId");
		String  tenantId = (String)ruleMap.get("tenantId");

		servParamMap.put("deptId", deptId);
		servParamMap.put("userId", userId);
		servParamMap.put("queueId", queueId);
		servParamMap.put("updateTime", createTime);
		servParamMap.put("authorId",userId);
		servParamMap.put("tenantId", tenantId);
		servParamMap.put("updateAccept",commParam.get("updateAccept"));
		servParamMap.put("opCode", commParam.get("opCode"));
		servParamMap.put("opNote", commParam.get("opNode"));//
		servParamMap.put("opType", commParam.get("opType"));//
		servParamMap.put("sourceType", sourceType);//

		//根据科室ID 查询租户ID
        Map<String,Object> ptMap = new HashMap<String,Object>();
		ptMap.put("userId",userId);
		ptMap.put("tenantId",tenantId);
		ptMap.put("queueId",queueId);
		List<String> statulist = new ArrayList<String>();
		statulist.add(Constants.PATIENT_QUEUESCHEME_USER_STATUS_NOMAL);
		ptMap.put("status", statulist);
		List<PatientQueueScheme> queueSchemeList = patientQueueSchemeDao.selectByUserId(ptMap);
		String ptSchemeId = null;
		if(CollectionUtils.isEmpty(queueSchemeList)){
			logger.error("error --> 用户不存在");
			return;
		}
		ptSchemeId =  queueSchemeList.get(0).getId();
		//随访修改  取出手机号问卷
		if (Constants.SCHEME_BUSI_TYPE_0 == schemeBusiType) {
			servParamMap.put("contentData",questions);

			ptMap.clear();
			ptMap.put("seqNo", Constants.TASK_SEQ_FOR_INIT);
			ptMap.put("ptSchemeId",ptSchemeId);
			// 查询taskid
			List<PatientTask> taskList = patientTaskDao.select(ptMap);
			String taskId ="";
			if (!CollectionUtils.isEmpty(taskList)) {
				taskId = taskList.get(0).getId();

				// 任务审核状态
		        String taskAuditStatus = taskList.get(0).getAuditStatus();
		        if (StringUtils.isEmpty(taskAuditStatus)) {
		            taskAuditStatus = Constants.PATIENT_TASK_AUDIT_STATUS_INIT;
		        } else if (Constants.PATIENT_TASK_AUDIT_STATUS_NORMAL.equals(taskAuditStatus)) {
		            // 已审核通过
		            if (Constants.PATIENT_SOURCE_TYPE_SCAN.equals(sourceType)) {
		                // 诊间扫码渠道
		                throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_PT_SACN_SYNC_DATA_FOR_AUDITED,
		                        "患者填写信息医生已确认，无法同步修改！"));
		            }
		        }
			}

			servParamMap.put("ptSchemeId", ptSchemeId);
			servParamMap.put("taskId", taskId);
			servParamMap.put("type", Constants.QUESTIONNAIRE_TYPE_0);

			//问卷查询
			Map<String,Object> contentParam = new HashMap<String,Object>();
			contentParam.put("schemeId",ruleMap.get("schemeId"));
			contentParam.put("queueId", queueId);
			Map<String,Object> contMapOut = followQueueSerivce.qryQueueSchemePatientAddContent(contentParam);
//	        List<Object> contMapOutList =patientService.getContTempDataByTaskId(queueId,taskId) ;
			Map<String,Object> contentMapTemp = questionContentConvert(questions,queueId,contMapOut,Constants.MQ_MESSAGE_GET_FROM_SCAN);
			servParamMap.put("questions",contentMapTemp);

			patientService.modTaskContentData(servParamMap);
        } else if (Constants.SCHEME_BUSI_TYPE_1 == schemeBusiType) {
        	//诊疗修改
	        Map<String, Object> taskInfo = new HashMap<String,Object>();
	        Map<String, Object> param = new HashMap<String,Object>();
	        servParamMap.put("followQueueId",queueId);
	        servParamMap.put("patientId", (String)servParamMap.get("userId"));
	        servParamMap.put("ptSchemeId", ptSchemeId);
	        String ptTaskId ="";
	        Map<String, Object> queueMapIn = new HashMap<String, Object>();
            queueMapIn.put("id", ptSchemeId);
            queueMapIn.put("queueId", queueId);
            List<PatientQueueScheme> pqsList = patientQueueSchemeDao.selectPatientByCondition(queueMapIn);
            if (!CollectionUtils.isEmpty(pqsList)) {
            	PatientQueueScheme pqsVo = pqsList.get(0);
            	ptTaskId = pqsVo.getArchiveTaskId();
            }
	        taskInfo.put("ptTaskId", ptTaskId);
	        taskInfo.put("updateAuname",userId);//
	        param.put("oprInfo", servParamMap);
	        param.put("questions", questions);
	        param.put("taskInfo", taskInfo);

	        //根据配置规则 转换问卷内容
	        //门诊扫码建档   增加问卷字段根据配置关系 映射  start
	        String archiveTemplId = (String) ruleMap.get("archiveTemplId");
	        String archiveTemplIdArr[] = archiveTemplId.split(Constants.COMMA_SPLIT_STR);
	        List<String> archiveTemplIdList = java.util.Arrays.asList(archiveTemplIdArr);
	        Map<String, Object> contMapIn = new HashMap<String, Object>();
	        contMapIn.put("templIdList", archiveTemplIdList);
	        Map<String, Object> contMapOut = patientTreatService.getContentTemplData(contMapIn); //问卷
	        Map<String,Object> contentMapTemp = questionContentConvert(questions,queueId,contMapOut,Constants.MQ_MESSAGE_GET_FROM_SCAN);
	        param.put("questions",contentMapTemp);
	        //门诊扫码建档   增加问卷字段根据配置关系 映射  end
    		patientTreatService.modifyPtArchivesData(param);
        }
		logger.info("out consumerModifyPatientByScan");
	}

	@SuppressWarnings("unchecked")
	private JSONObject questionContentConvert(JSONObject questions, String queueId,Map<String, Object> contMapOut,String mode) {
		logger.info("in contentConverByUpdate");
		JSONObject contentMapTemp = new JSONObject();//转换后的问卷 id和答案：object

		String modeStr = "";
		if(Constants.MQ_MESSAGE_GET_FROM_SCAN.equals(mode)){
			modeStr = "receiveRel";
		}else if(Constants.MQ_MESSAGE_PUSH_TO_SCAN.equals(mode)){
			modeStr = "pushRel";
		}

		Map<String,Object> contentMap = new HashMap<String,Object>();//转换后的问卷 id：object
		if(null !=contMapOut && null!=contMapOut.get("questiones")){
			List<Object> conDataList = (List<Object>)contMapOut.get("questiones");
			contentMap = ToolUtils.tranferContentToMap(conDataList);
			for (Map.Entry<String,Object> entry : contentMap.entrySet()) {
				String key = entry.getKey();
				//此时 key 先从宝宝中取
				JSONObject value = (JSONObject)entry.getValue();
				String relId ="";
				/**
				 * 字段级规则配置 可不配 默认全部按id接收
				 * receiveRelations 接收其他问卷消息  ， pushRelations:推送到客户端问卷字段id
				 * {"id":"Pub1100002","rules":[{"queueId":"",
				 * 								"type":"",
				 * 								"receiveRel":"Pub1100011_,",
				 * 								"pushRel":"Pub1100011_"}] //针对某队列 接收推送规则 0和空:默认全接收和推送  1:只接收 2:只推送  3：都不
				 *
				 */
				Object answer = "";
				JSONArray ruleArr = value.getJSONArray("rules");
				String type = "";
				if(null!=ruleArr){
					for(int l = 0 ;l < ruleArr.size();l++){
						String refQueueId = ruleArr.getJSONObject(l).getString("queueId");
						if(queueId.equals(refQueueId)){
							//有队列映射关系 则继续判断映射关联字段
							relId = ruleArr.getJSONObject(l).getString(modeStr);
							type = ruleArr.getJSONObject(l).getString("type");
							break;
						}
					}
				}

				//根据ruletype 判断是否接收或推送
				if(Constants.MQ_MESSAGE_GET_FROM_SCAN.equals(mode)){
					//type为空 (接收和推送都支持) 或者 接收权限
					if(StringUtils.isEmpty(type) || Constants.MQ_QUESTION_ID_GET.equals(type)){
						if(StringUtils.isEmpty(relId)){
							answer = questions.get(key);
						}else{
							answer = questions.get(relId);
						}
						contentMapTemp.put(key,answer);
					}
				}else if(Constants.MQ_MESSAGE_PUSH_TO_SCAN.equals(mode)){
					//type为空 (接收和推送都支持) 或者 推送权限
					if(StringUtils.isEmpty(type) || Constants.MQ_QUESTION_ID_PUSH.equals(type)){
						answer = questions.get(key);
						if(StringUtils.isEmpty(relId)){
							contentMapTemp.put(key,answer);
						}else{
							contentMapTemp.put(relId,answer);
						}
					}
				}
			}
		}
		logger.info("out contentConverByUpdate-->"+contentMapTemp.toJSONString());
		return contentMapTemp;
	}

	@Override
	public void sendFollowGuidance(Map<String, Object> argMap) throws Exception {
		//不发送随访指导。
	}
/*
	@Override
	public void sendFollowGuidance(Map<String, Object> argMap) throws Exception {
		logger.info("in sendFollowGuidance-->");
		try{
			Object schemeBusiObj =argMap.get("schemeBusiType");
			Integer schemeBusiType = null;
			if(StringUtils.isEmpty(schemeBusiObj)){
				schemeBusiType = Constants.SCHEME_BUSI_TYPE_0 ;
			}

	        String sourceType = (String) argMap.get("sourceType");// 来源渠道
	        String taskId = (String) argMap.get("taskId");
	        String queueId = (String) argMap.get("queueId");

	        if(!Constants.PATIENT_SOURCE_TYPE_DOOR.equals(sourceType)){
				logger.error("out sendFollowGuidance--> 不是web端医生填写 不需要同步");
	            return;
			}

	        JSONObject quesMap = (JSONObject) argMap.get("contentData");
	        if (null == quesMap || 0 == quesMap.size()) {
	            logger.error("无问题--答案记录");
	            return;
	        }

			Map<String,Object> ruleMap = dataSynchPermission(queueId,Constants.OP_CODE_1122, Constants.PATIENT_DATA_RULE_TYPE_PUSH);
			if(null==ruleMap || ruleMap.isEmpty() || !ruleMap.containsKey("flag") || !(boolean) ruleMap.get("flag"))	{
				logger.error("队列没有配置推送权限[queueId="+queueId);
				return;
			}

			//根据taskid查询本次问卷 是否有随访指导类型 (tempType=5)
			Map<String, Object> queryParam = new HashMap<String, Object>(); //ctvList.get(0);
			Map<String, Object> outCtvMap = new HashMap<String, Object>(); //ctvList.get(0);
			if (Constants.SCHEME_BUSI_TYPE_0 == schemeBusiType) {
				queryParam.clear();
				queryParam.put("taskId",taskId);
				// 查询随访方案任务内容
				List<PatientTaskContent> ptcList = patientTaskConDao.selectContentByTaskId(queryParam);
				if (CollectionUtils.isEmpty(ptcList)) {
					logger.error("out consumerTaskContDataByScan-->没有任务内容");
					return;
				}
				List<Object> conDataList = new ArrayList<Object>();
				int ipt = 0;
		        int isize = ptcList.size();
		        Map<String, Object> dataOut = new HashMap<String, Object>();
				for (ipt = 0; ipt < isize; ipt++) {
		            PatientTaskContent ptaskc = ptcList.get(ipt);
		            String templVersionId = ptaskc.getTemplVersionid();

		            if(!Constants.QUESTIONNAIRE_TYPE_5.equals(ptaskc.getTemplType())){ //只取随访指导
		            	continue;
		            }

		            queryParam.clear();
		            queryParam.put("templVersionId",templVersionId);
		            dataOut = patientService.getContTemplData(queryParam);
		            if (null != dataOut.get("contData")) {
		                conDataList.add(dataOut.get("contData"));
		            }
		        }
				outCtvMap.put("questiones", conDataList);
			}else if (Constants.SCHEME_BUSI_TYPE_1 == schemeBusiType) {
				queryParam.clear();
				queryParam.put("taskId",taskId);
				List<TrTaskContent> list = trTaskContentDao.getTaskContentByTaskId(queryParam);
	            if (list != null && list.size() > 0) {
	                String archiveTemplId = "";
	                for (int i = 0; i < list.size(); i++) {
	                    TrTaskContent tc = list.get(i);
	                    archiveTemplId = archiveTemplId + "," + tc.getTemplId();
	                }
	                String archiveTemplIdArr[] = archiveTemplId.split(Constants.COMMA_SPLIT_STR);
	                List<String> archiveTemplIdList = java.util.Arrays.asList(archiveTemplIdArr);
	                Map<String, Object> contMapIn = new HashMap<String, Object>();
	                contMapIn.put("templIdList", archiveTemplIdList);

	                contMapIn.put("questionnaireType", Constants.QUESTIONNAIRE_TYPE_5);
	                Map<String, Object> contMapOut = patientTreatService.getContentTemplData(contMapIn);
	                outCtvMap.put("questiones", contMapOut.get("questiones"));
	            }
			}

			//根据问卷字段id 映射规则
			Map<String,Object> contentMapTemp = questionContentConvert(quesMap,queueId,outCtvMap,Constants.MQ_MESSAGE_PUSH_TO_SCAN);
			if(MapUtils.isEmpty(contentMapTemp)){
				logger.error("out sendFollowGuidance--> contentMapTemp is empty");
				return ;
			}
			Map<String,Object> param = new HashMap<String,Object>();
			param.putAll(argMap);
			param.put("questions",contentMapTemp);

			Map<String,Object> synchMap = new HashMap<String,Object>();
			synchMap.put("sourceType",Constants.PATIENT_SOURCE_TYPE_DOOR);
			synchMap.put(Constants.MQ_MESSAGE_BODY,param);
			//业务类型
			synchMap.put(Constants.MQ_MESSAGE_TYPE,Constants.CONSUMER_TYPE_FOLLOWUP_GUIDE_TO_SCAN);
			HttpUtil.postData(PropertiesUtils.getProperty("redirectUrl2"),JSON.toJSONString(synchMap));
		}catch(Throwable e){
			logger.error("error -->", e);
		}
	}
*/

	//数据同步权限
	private Map<String,Object> dataSynchPermission(String queueId,String opCode,String mode) throws Exception{
		boolean flag = false;
		Map<String,Object> queryParam = new HashMap<String,Object>();
        queryParam.put("queueId",queueId);
        queryParam.put("status",Constants.COMMON_STATUS_NOMAL);
//        queryParam.put("channel",sourceType);
		Map<String,Object> ruleMap = queueDao.selectQueueDataRules(queryParam);
		if (null == ruleMap)	{
			ruleMap = new HashMap<String,Object>();
			return ruleMap;
		}

		String updateCondition ="";

		if(null == ruleMap || null == ruleMap.get("updateCondition")){
			logger.info("队列没有配置同步权限数据-->[queueId="+queueId);

			flag = false;
			ruleMap.put("flag",flag);
			ruleMap = new HashMap<String,Object>();
			return ruleMap;
		}

		updateCondition = ruleMap.get("updateCondition").toString();

		//是否需要推送
		String permission = null;
		String busiId ="";
		JSONObject updateConditionJson = null;
		if(null != JSON.parseObject(updateCondition)){
			updateConditionJson = JSON.parseObject(updateCondition);
			Object conditionObj = updateConditionJson.get(Constants.MQ_QUESTIONNAIRE_RULE_NAME);
			if(null != conditionObj && conditionObj instanceof JSONObject){
				permission = ((JSONObject)conditionObj).getString(opCode);
			}
			Object busiObj = updateConditionJson.get(Constants.MQ_SYNCH_BUSI_RULE_NAME);
			if(null != busiObj && busiObj instanceof JSONObject){
				busiId = ((JSONObject)busiObj).getString(opCode);
			}
		}


		if(null==permission || !permission.toUpperCase().contains(mode)){
			logger.error("队列没有配置权限[queueId="+queueId);
			flag = false;
		}else{
			flag = true;
		}

		ruleMap.put("busiId",busiId);
		ruleMap.put("permission",permission);
		ruleMap.put("flag",flag);
		return ruleMap;
	}

	/**
	 * @保存临时任务 并返回任务id
	 * @param param
	 * @return
	 * @throws Exception
	 */
	private Map<String,Object> saveTempTaskAndRspTaskId(Map<String,Object> param) throws Exception{
			Map<String,Object> rspMap =  new HashMap<String,Object>();
			HashMap<String, Object> paramMap = new HashMap<String, Object>();

	        String ptSchemeId = (String)param.get("ptSchemeId");
	        String queueId = (String)param.get("queueId");
	        String userId = (String)param.get("userId");
	        String tenantId = (String)param.get("tenantId");
	        String updateTime = (String)param.get("updateTime");
	        String updateAccept = (String)param.get("updateAccept");

	        paramMap.put("ptSchemeId",ptSchemeId);
	        paramMap.put("userId",userId);
	        paramMap.put("queueId",queueId);
	        paramMap.put("seqNoOrderAsc", "1");
	        paramMap.put("currDate", DateUtil.getCurrDate());

            if (!StringUtils.isEmpty(queueId)) {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("id", queueId);
                FollowQueue queue = followQueueSerivce.getQueueDetailByQueueId(map);
                if (null == queue) {
                    throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_QUEUE_NOT_EXIST, "根据队列id查询无此队列信息！"));
                }
                String queueUserType = queue.getQueueUsertype();
                if (Constants.QUEUE_USER_TYPE_PARTURIENT.equals(queueUserType)) {
                    paramMap.put("taskFlag", "1");
                }
            }
	        List<Object> ptList = patientService.qryPatientTaskList(paramMap);

	        if(!CollectionUtils.isEmpty(ptList)){
	        	Object task =  ptList.get(ptList.size()-1);
	        	if(task instanceof Map<?,?>){
	        		String taskId = (((Map<?,?>)task).get("taskId")).toString();

	        		paramMap.clear();

	        		Map<String,Object> taskMap = new HashMap<String,Object>();
	        		Map<String,Object> opInfoMap = new HashMap<String,Object>();
	        		Map<String,Object> sessionMap = new HashMap<String,Object>();


	        		sessionMap.put("authorName","");
	        		sessionMap.put("authorId",userId);
	        		sessionMap.put("tenantId",tenantId);

	        		opInfoMap.put("updateTime",updateTime);
	        		opInfoMap.put("updateAccept",updateAccept);
	        		opInfoMap.put("opCode",Constants.OP_CODE_1018);
	        		opInfoMap.put("opType","1");
	        		opInfoMap.put("opNote","诊间扫码同步主诉，随访后台新增了临时随访任务");

	        		taskMap.put("ptTaskId",taskId);
	        		taskMap.put("followQueueId",queueId);
	        		taskMap.put("ptSchemeId",ptSchemeId);
	        		taskMap.put("patientId",userId);

	        		paramMap.put("sessionInfo", sessionMap);
	                paramMap.put("oprInfo", opInfoMap);
	                paramMap.put("taskInfo", taskMap);

	                paramMap.put("sourceType",Constants.PATIENT_SOURCE_TYPE_SCAN);
	                // taskInfo
	        		Map<String,Object> retMap = patientInfoHisService.saveNewTempPatientTask(paramMap);
	        		if(CollectionUtils.isEmpty(retMap)){
	        			rspMap.putAll(retMap);
	        		}
	        	}

	        }

	        return rspMap;
	}
}
